//
//  CustomerServiceViewController.m
//  QinrenManagers
//
//  Created by easaa on 15/5/29.
//  Copyright (c) 2015年 easaa. All rights reserved.
//

#import "CustomerServiceViewController.h"

#import "CustomerDetailsViewController.h"

#import "CustomerListModel.h"

#import "UIImageView+EMWebCache.h"

@interface CustomerServiceViewController () <UITableViewDataSource,UITableViewDelegate,UISearchDisplayDelegate>
{
     BOOL _needRefresh;
}
@property (nonatomic, strong) UITableView    * customerTableView;
    
@property (nonatomic, strong) NSMutableArray * dataSourceArry;

@property (nonatomic, strong) NSMutableArray * customerNameArry;
    
   /**搜索结果数组*/
@property (nonatomic, strong) NSMutableArray * resultArray;
    
@property (nonatomic, strong) UISearchBar    * searchBar;
    
@property (nonatomic, strong) UISearchDisplayController * searchController;

/**分页*/
@property (nonatomic, assign) NSInteger pageIndex;

@end

@implementation CustomerServiceViewController

- (instancetype)init
{
    self = [super init];
    if (self) {
        _dataSourceArry = [NSMutableArray array];
        _resultArray = [NSMutableArray array];
        _customerNameArry = [NSMutableArray array];
        _pageIndex = 1;
    }
    return self;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    // Do any additional setup after loading the view.

    [self requestForCustomerData];
    
    [self creatUI];
    
}

- (void)requestForCustomerData {
    
    EAHttpAPIClient *manager = [EAHttpAPIClient manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    User *user = [User sharedUser];
    
    NSDictionary *parameters = @{@"employee_id":user.employee_id,@"pagesize":@"10",@"pageindex":[NSString stringWithFormat:@"%ld",(long)_pageIndex]};
    NSLog(@"%@",parameters);
    [manager GetWithParameters:parameters method:@"search.user.info" success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSString *resposeString ;
        if ([responseObject isKindOfClass:[NSData class]]) {
            resposeString = [[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding];
        }else
            resposeString = responseObject;
        
        NSString *jsonString = [DataParser parseString:resposeString];
        id dictionary = [JSONKit jsonToArrayOrDictionary:jsonString];
        NSLog(@"客户列表的dictonary :%@",[dictionary description]);
        
        if ([[dictionary objectForKey:@"verification"]intValue] == 1)
        {
            if (_needRefresh) {
                [SVProgressHUD showSuccessWithStatus:@"请求数据中"];
                [_dataSourceArry removeAllObjects];
            }

            for (NSDictionary *dataDic in dictionary[@"data"]) {
                
                CustomerListModel * customerListModel = [[CustomerListModel alloc]init];
                [customerListModel setValuesForKeysWithDictionary:dataDic];
                
                [_dataSourceArry addObject:customerListModel];
                
                [_customerNameArry addObject:customerListModel.customer_truename];
                
            }
            [_customerTableView reloadData];
            
            if ([dictionary[@"total"] integerValue] < 10) {
                
                //[_personalTableView.footer resetNoMoreData];
#warning 试一下吊环顺序
                [_customerTableView.footer endRefreshing];
                [_customerTableView.header endRefreshing];
                [_customerTableView.footer noticeNoMoreData];
                return ;
            }

            
            
        }
        else
        {
            NSString *error = [dictionary objectForKey:@"error"];
            [SVProgressHUD showWithMaskType:SVProgressHUDMaskTypeClear];
            [SVProgressHUD showErrorWithStatus:error];
        }
        
        [_customerTableView.footer endRefreshing];
        [_customerTableView.header endRefreshing];
        [_customerTableView.footer noticeNoMoreData];
        
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        [SVProgressHUD showWithMaskType:SVProgressHUDMaskTypeClear];
        [SVProgressHUD showErrorWithStatus:[error localizedDescription]];
        [_customerTableView.footer endRefreshing];
        [_customerTableView.header endRefreshing];

    }];
    
}


//- (void)creatData
//{
//    _dataSourceArry = [NSMutableArray array];
//    
//    _dataSourceArry = [NSMutableArray arrayWithObjects:[NSMutableArray arrayWithObjects:@"阿里郎",@"爱撒",@"a啊是的",nil],[NSMutableArray arrayWithObjects:@"basda",@"博阿斯达说",@"棒棒哒",nil],[NSMutableArray arrayWithObjects:@"casda",@"擦阿斯达说",@"擦看哒",@"出来的",nil],[NSMutableArray arrayWithObjects:@"dasda",@"的阿斯达说",@"冬天看哒",@"度的",nil],nil];
//    
//    _resultArray = [NSMutableArray array];
//}

- (void)creatUI
{
    //搜索框
    //_searchBar=[[UISearchBar alloc]initWithFrame:CGRectMake(0, 64, SCREEN_W, 44)];
    _searchBar=[[UISearchBar alloc]initWithFrame:CGRectMake(0, 0, SCREEN_W, 44)];
    
     _searchBar.placeholder = @"搜索";
    
    //_searchBar.backgroundColor = [UIColor greenColor];
   
        //搜索结果展示
    // 用 searchbar 初始化 SearchDisplayController
    // 并把 searchDisplayController 和当前 controller 关联起来
    _searchController = [[UISearchDisplayController alloc] initWithSearchBar:_searchBar contentsController:self];
    
    _searchController.delegate = self;
    // searchResultsDataSource 就是 UITableViewDataSource
    _searchController.searchResultsDataSource = self;
    // searchResultsDelegate 就是 UITableViewDelegate
    _searchController.searchResultsDelegate = self;
    
    //主界面数据展示
   // _customerTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(_searchBar.frame), SCREEN_W, SCREEN_H-64-44) style:UITableViewStyleGrouped];
    _customerTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 3, SCREEN_W, SCREEN_H-64) style:UITableViewStylePlain];
    
 
    //_customerTableView.backgroundColor = [UIColor yellowColor];
    _customerTableView.dataSource=self;
    _customerTableView.delegate=self;
    _customerTableView.tableFooterView = [[UIView alloc]initWithFrame:CGRectZero];
//    _customerTableView.tableHeaderView = [[UIView alloc] init];
//    _customerTableView.tableHeaderView.backgroundColor = [UIColor yellowColor];
    __weak typeof(self) weakSelf = self;
    [_customerTableView addLegendHeaderWithRefreshingBlock:^{
        [weakSelf headerRefresh];
    }];
    [_customerTableView addLegendFooterWithRefreshingBlock:^{
        [weakSelf footerRefresh];
    }];

    
    //_customerTableView.tableHeaderView = _searchBar;
    
    //[self.view addSubview:_searchBar];
    [self.view addSubview:_customerTableView];
    
}

- (void)headerRefresh{
    _needRefresh = YES;
    _pageIndex = 1;
    [self requestForCustomerData];
}
- (void)footerRefresh{
    _needRefresh = NO;
    _pageIndex ++;
    [self requestForCustomerData];
}


#pragma mark - ---------------------------Search Delegate----------------------------

//只要用户在searchbar中输入内容就会触发该方法
- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString
{
#if 0
    //每次搜索之前，清空searchResults
    [_resultArray removeAllObjects];
    NSLog(@"%@", searchString);
    
    for (NSArray *section in _dataSourceArry)
    {
        //通过谓词过滤数据
        NSPredicate *p = [NSPredicate predicateWithFormat:@"self contains[c] %@", searchString];
        
        NSArray *a = [section filteredArrayUsingPredicate:p];
        
        //实现排序
        //self == 排序条件
        //NO    == 升序(YES)or降序(NO)
        NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"self" ascending:NO];
        NSArray *s = [a sortedArrayUsingDescriptors:@[sort]];
        NSLog(@"%@", s);
        [_resultArray addObjectsFromArray:s];
    }
   
    return YES;
#endif
    
    //每次搜索之前，清空searchResults
    [_resultArray removeAllObjects];
    NSLog(@"%@", searchString);
    
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF contains[c] %@",searchString];//用于过滤
    _resultArray = [NSMutableArray arrayWithArray:[_customerNameArry filteredArrayUsingPredicate:predicate]];
    
    return YES;

}


#pragma mark- ------------------------UITableView 代理实现--------------------------
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    
    if(tableView != _customerTableView)
    {
        return 1;
    }
    
//    return _dataSourceArry.count;
    return 1;
    
}

//设置rows的行数
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if(tableView != _customerTableView)
    {
        return [_resultArray count];
    }
    else
        return [_dataSourceArry count];
}


//Cell的相关设置
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString * cellName=@"cell";
    
    UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:cellName];
    if(cell==nil)
    {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellName];
    }
    if(tableView != _customerTableView){
        cell.textLabel.text=[_resultArray objectAtIndex:indexPath.row];
    }else{
        
        CustomerListModel *customerListModel = [_dataSourceArry objectAtIndex:indexPath.row];
        UIImageView *iconView = [[UIImageView alloc]initWithFrame:CGRectMake(10, 2, 40, 40)];
        [iconView sd_setImageWithURL:[NSURL URLWithString:customerListModel.icon] placeholderImage:[UIImage imageNamed:@"touxiang.jpg"]];
//        cell.imageView.layer.cornerRadius = CGRectGetHeight(cell.imageView.frame)/2;
//        cell.imageView.clipsToBounds = YES;
        [cell.contentView addSubview:iconView];
        
        UILabel * nameLabel = [[UILabel alloc]initWithFrame:CGRectMake(60, 2, 200, 40)];
        nameLabel.text =customerListModel.customer_truename;
        [cell.contentView addSubview:nameLabel];
        
        
        
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath*)indexPath

{
    CustomerDetailsViewController * customerDetailsViewController = [[CustomerDetailsViewController alloc]init];
    
    CustomerListModel *customerListModel = [_dataSourceArry objectAtIndex:indexPath.row];
    
    customerDetailsViewController.customer_id = customerListModel.customer_id;
    customerDetailsViewController.title = customerListModel.customer_truename;
    
    [self.navigationController pushViewController:customerDetailsViewController animated:NO];

}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 50;
}


//设置section的title
//-(NSString*)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
//{
//    if(tableView != _customerTableView){
//        return @"搜索结果";
//    }
//    else{
//
//        return [NSString stringWithFormat:@"%c",97+section];
//    }
//}
//- (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
//{
//    return 30.0;
//}
//

#pragma mark-------------------------------设置索引条--------------------------------
////设置索引条
//-(NSArray*)sectionIndexTitlesForTableView:(UITableView *)tableView
//{
//    NSMutableArray * titles=[[NSMutableArray alloc]init];
//    //加上了放大镜，如果搜索框加到view上，让其不动的话，不用加
//    [titles addObject:UITableViewIndexSearch];
//    //加入其他内容
//    for(int i=97;i<123;i++)
//    {
//        [titles addObject:[NSString stringWithFormat:@"%c",i]];
//    }
//    return titles;
//}

//设置索引条对应关系
//如果不加放大镜。这个方法就不需要。
//-(NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
//{
//    if(index==0)
//    {
//        //index是索引条的序号。从0开始，所以第0 个是放大镜。如果是放大镜坐标就移动到搜索框处
//        [tableView scrollRectToVisible:_searchBar.frame animated:NO];
//        return -1;
//    }else{
//        //因为返回的值是section的值。所以减1就是与section对应的值了
//        return index-1;
//    }
//}


@end
